769C - Cycle In Maze - CodeForces Solution


*special problem dfs and similar graphs greedy shortest paths *1700

Please click on ads to support us..

C++ Code:

#include<bits/stdc++.h>
using namespace std;
#define int long long
#define pii pair<int, int>
const int maxn = 1e3+5;
int n, m, k;
pii st;
char a[maxn][maxn];
int l[maxn][maxn], d[maxn][maxn];
int moveX[]={1,0,0,-1};
int moveY[]={0,-1,1,0};
string dr="DLRU", ans;
signed main() {
    ios_base::sync_with_stdio(false);
	cin.tie(NULL);
    cin >> n >> m >> k;
    if (k%2==1)
    {
    	cout<<"IMPOSSIBLE";
    	return 0;
    }
    for (int i=1; i<=n; i++)
    {
    	for (int j=1; j<=m; j++)
    	{
    		cin >> a[i][j];
    		if (a[i][j]=='X') 
    			{
    				st={i,j};
    				a[i][j]='.';
    			}
    	}
    }
    l[st.first][st.second]=1;
    d[st.first][st.second]=1;
	queue<pii>q;
	q.push({st.first,st.second});
	while (!q.empty())
	{
		int s=q.front().first;
		int e=q.front().second;
		q.pop();
		for (int i=0; i<4; i++)
		{
			int u=s+moveX[i];
			int v=e+moveY[i];
			if (u<1||u>n||v<1||v>m) continue;
			if (d[u][v]==0&&a[u][v]=='.')
				{
					l[u][v]=l[s][e]+1;
					d[u][v]=1;
					q.push({u,v});
				}
		}
	}
    while (k)
    {
    	int tx, ty;
    	bool flag=true;
    	for (int i=0; i<4; i++)
    	{
    		tx=st.first+moveX[i];
    		ty=st.second+moveY[i];
    		if (a[tx][ty]=='.'&&l[tx][ty]<=k)
    		{
    			ans+=dr[i];
    			st.first=tx;
    			st.second=ty;
    			flag=false;
    			break;
    		}
    	}
    	if (flag) {
    		cout<<"IMPOSSIBLE";
    		return 0;
    	}
    	k--;
    }
    cout<<ans;
}


	 			     			    	 	 	   		 			


Comments

Submit
0 Comments
More Questions

1325D - Ehab the Xorcist
552B - Vanya and Books
1722E - Counting Rectangles
168A - Wizards and Demonstration
168B - Wizards and Minimal Spell
7A - Kalevitch and Chess
912B - New Year's Eve
1537C - Challenging Cliffs
879B - Table Tennis
1674E - Breaking the Wall
1282A - Temporarily unavailable
1366C - Palindromic Paths
336A - Vasily the Bear and Triangle
926A - 2-3-numbers
276D - Little Girl and Maximum XOR
1253C - Sweets Eating
1047A - Little C Loves 3 I
758D - Ability To Convert
733A - Grasshopper And the String
216A - Tiling with Hexagons
1351B - Square
1225A - Forgetting Things
1717A - Madoka and Strange Thoughts
1717B - Madoka and Underground Competitions
61B - Hard Work
959B - Mahmoud and Ehab and the message
802G - Fake News (easy)
1717C - Madoka and Formal Statement
420A - Start Up
1031A - Golden Plate